<?
  header("Cache-Control:no-cache");
  header("Pragma:no-cache");

  session_start();
  
  include "common/db_conn.php";

  $sb_idx = $_GET["sd_idx"];
  $page = $_GET["page"];
  $curpage = $_GET["curpage"];
  
  if ($sd_idx == "")
    $sd_idx = 1;
  if ($page == "")
    $page = 1;
  
  if ($curpage == "") {
    $curpage = 1;
  }
  
  $sm_idx = $_SESSION["sm_idx"];
  //echo("sm_idx[$sm_idx]<br>");
  
  if ($sm_idx == "") {
    echo("ILLEGAL ACCESS<br>");
    exit(0);
  }
  
  $query_d = "select count(*) cnt from sv_qlist";
  $result_d = mysql_query($query_d);
  $rows_d = mysql_fetch_array($result_d);
  $q_cnt = $rows_d["cnt"];
  
  $query_d = "select sd_idx, sd_text from sv_dlist where sd_idx = $sd_idx";
  $result_d = mysql_query($query_d);
  $rows_d = mysql_fetch_array($result_d);
  $num_rows_d = mysql_num_rows($result_d);
  
  if ($num_rows_d != 1) {
    echo("Illegal Access!");
    exit(0);
  }
  
  $query_m = "select sm_state from sv_member where sm_idx = $sm_idx";
  $result_m = mysql_query($query_m);
  $rows_m = mysql_fetch_array($result_m);
  $sm_state = $rows_m["sm_state"];
  
  //echo("sm_state[$sm_state]<br>");
  if ($sm_state == 1) {
?>
<script>
  location.href = "close.html";
</script>
<?  
    exit(0);
  }
  
  $sd_text = stripslashes($rows_d["sd_text"]);
  
  $query_q = "select  count(*) cnt from sv_qlist where sd_idx = $sd_idx";
  $result_q = mysql_query($query_q);
  $rows_q = mysql_fetch_array($result_q);
  $count = $rows_q["cnt"];

  //echo("sd_idx[$sd_idx] sd_text[$sd_text] count[$count]<br>");
  
  $perpage = 5;
  $page_start = ($page - 1) * $perpage;
  $query_q = "select sq_idx, sq_no, sq_text, sq_type, sq_from, sq_to from sv_qlist where sd_idx = $sd_idx order by sq_no asc";
  $query_q .= " limit $page_start, $perpage";
  $result_q = mysql_query($query_q);
  $num_rows_q = mysql_num_rows($result_q);
  
  $page_total = floor(($q_cnt - 1) / $perpage) + 1;


  
  $query_q1 = "select count(*) cnt from sv_qlist";
  $result_q1 = mysql_query($query_q1);
  $rows_q1 = mysql_fetch_array($result_q1);
  $quest_cnt = $rows_q1["cnt"];
  
  $query_r = "select count(distinct sq_idx) cnt from sv_response where sm_idx = $sm_idx";
  $result_r = mysql_query($query_r);
  $rows_r = mysql_fetch_array($result_r);
  $solved_cnt = $rows_r["cnt"];
  
  //echo("quest_cnt [$quest_cnt] solved_cnt[$solved_cnt]<br>");
  
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, width=device-width, height=device-height" />
<link href="common/style.css" rel="stylesheet" type="text/css" media="all" />
<script>
  var first = true;
  function validation(check)
  { // check: 1 - just for check
    var count = document.frm.count.value;
    var sr_answer;
    
    console.log("count: " + count);
    for  (i = 0; i < count; i++)
    {
      var type = eval("document.frm.sq_type_"+i+".value");
      var subtype = eval("document.frm.sq_subtype_"+i+".value");
      var sq_from = eval("document.frm.sq_from_"+i+".value");
      var sq_to = eval("document.frm.sq_to_"+i+".value");
      
      console.log("i: " + i + " type: " + type + " subtype: " + subtype);
      
      bPass = false;
      
      if (type < 3) {
        if (subtype == 0) {
          var tmp = "document.frm.sr_answer_"+i;
          var len = eval(tmp+".length");
          console.log("len: " + len);

          for (var j = 0; j < len; j++) {
            console.log("j: " + j + " eval: " + eval(tmp+"["+j+"].checked"));
            if (eval(tmp+"["+j+"].checked")) {
              bPass = true;
              break;
            }
          }
          
          if  (bPass == false) {
            if (!check)
              alert("응답하지 않았습니다.");
            return false;
          }
        } else if (subtype == 1) {
          var nums = 0;
          var  len = eval("document.frm.sr_answer_count_"+ i + ".value" );
          console.log("len: " + len + " sq_from: " + sq_from + " sq_to: " + sq_to);

    //      var tmp = "document.frm.sr_answer_"+i;
          console.log("subtype: " + subtype + " ..." + tmp+"["+j+"].value");
          for (var j = 0; j <= len; j++) {
            console.log("value - " + document.getElementById("sr_answer_"+i+"_"+(j+1)).checked);
            if (document.getElementById("sr_answer_"+i+"_"+(j+1)).checked == true) {
              nums++;
            }
          }
          
          console.log("nums = " + nums);
          
          if (nums >= sq_from && nums <= sq_to) 
            bPass = true;
          else 
            bPass = false;
            
          if  (bPass == false) {
            if (!check)
              alert("선택한 개수가 맞지 않습니다.");
            return false;
          }
        }
      } else if (type == 3) { // n
        console.log("value = " + eval("document.frm.sr_answer_"+i+".value"));
        var val = eval("document.frm.sr_answer_"+i+".value");
        
        if (val == "" || val < 0 || val > 10000) {
          if (!check)
            alert("올바른 숫자를 입력하세요.");
          return false;
        }
      } else if (type == 4) { // ym
        var val1 = eval("document.frm.year_" + i + ".value");
        var val2 = eval("document.frm.month_" + i + ".value");
        
        console.log("val1: " + val1 + " val2: " + val2);
        if (val1 == "" || val2 == "" | val1 < 0 || val1 > 100 || val2 < 0 || val2 > 12) {
          if (!check)
            alert("올바른 기간을 입력하세요.");
          return false;
        }
      }
    }
    return true;  
  }
  
  function goConfirm()
  {
    var ans = confirm("설문 응답을 완료하시겠습니까?");
    if  (ans == true) {
      document.getElementById("ifr").src = "s_proc.php?ptype=2";  
    } 
  }
</script>
</head>
<body onload="load()">
<h1><?=$sd_idx?>. <?=$sd_text?></h1>
<!--<button onClick="location.href='./q_list.html?sd_idx=<?=$sd_idx?>'">목록으로</button>-->

<!---
문제idx
답변no

-->
<form name="frm" method="post" target="ifr" action="s_proc.php" onSubmit="return validation(0);">
<input type="hidden" name="count" value="<?=$num_rows_q?>">
<input type="hidden" name="ptype" value="0">
<input type="hidden" name="curpage" value="<?=$curpage+1?>">

<? 
  for ($i = 0; $i < $num_rows_q; $i++) 
  {
    $rows_q = mysql_fetch_array($result_q);
    $sq_text = stripslashes($rows_q["sq_text"]);
    $sq_idx = $rows_q["sq_idx"];
    $sq_type = $rows_q["sq_type"];
    $sq_from = $rows_q["sq_from"];
    $sq_to = $rows_q["sq_to"];
    
    $query_r = "select sr_idx, sr_answer from sv_response where sm_idx = $sm_idx and sq_idx = $sq_idx";
    $result_r = mysql_query($query_r);
        
    if ($sq_to == "") { // 복수 응답형이 아닌 경우
      $rows_r = mysql_fetch_array($result_r);
      $sr_answer = $rows_r["sr_answer"];
      $sq_subtype = "0";
    } else {
      $sq_subtype = "1";
      $num_rows_r = mysql_num_rows($result_r);
      
      for ($s = 0; $s < 10; $s++) {
        $check_arr[$s] = false;
        $check_answer = "";
      }
      
      for ($s = 0; $s < $num_rows_r; $s++) {
        $rows_r = mysql_fetch_array($result_r);
        $sr_answer = $rows_r["sr_answer"];
        $sr_idx = $rows_r["sr_idx"];        
        
        //echo("sr_idx[$sr_idx] sr_answer[$sr_answer]<br>");
        $split = explode("|", $sr_answer);
        if (count($split) == 2) { // 기타 응답
          //echo("$split[0]->$split[1]<br>");
          $check_arr[$split[0]-1] = true;
          $check_answer = htmlspecialchars($split[1]);
          //$check_answer = str_replace("\"", "&quot;", $check_answer);
        } else {
          $check_arr[$sr_answer-1] = true;  
        }     

      }   
    }
    //echo("query_r[$query_r]");
    
    if ($sr_answer != "") {
      if ($sq_type == 4) {
        $year = floor($sr_answer / 12);
        $month = $sr_answer % 12;
      }
    }
?>
<p>
  <input type="hidden" name="sq_idx_<?=$i?>" value="<?=$sq_idx?>"> 
  <input type="hidden" name="sq_type_<?=$i?>" value="<?=$sq_type?>">
  <input type="hidden" name="sq_subtype_<?=$i?>" value="<?=$sq_subtype?>">
  <input type="hidden" name="sq_from_<?=$i?>" value="<?=$sq_from?>">
  <input type="hidden" name="sq_to_<?=$i?>" value="<?=$sq_to?>">
    <?=$rows_q["sq_no"]?>.    
<?
    switch ($sq_type) {
      case 0: // 선다형
?>
        <?=$sq_text?>
        <p> 
<?      
        
        $query_a = "select sa_idx, sq_idx, sa_text from sv_alist where sq_idx = $sq_idx order by sa_idx asc";
        $result_a = mysql_query($query_a);
        $num_rows_a = mysql_num_rows($result_a);
?>
        <input type="hidden" name="sr_answer_count_<?=$i?>" value="<?=$num_rows_a?>">
<?      
        for ($j = 0; $j < $num_rows_a; $j++)
        {
          $rows_a = mysql_fetch_array($result_a);
          if ($sr_answer != "" && $sr_answer== $j + 1) {
            $checked = " checked";
          } else {
            $checked = "";
          }
          
          if ($sq_to == "") {
?>
        <label><input type="radio" name="sr_answer_<?=$i?>" value="<?=($j+1)?>"<?=$checked?>><?=$rows_a["sa_text"]?></label><br>
<?        
          } else {
            if ($check_arr[$j] == true) {
              $checked = " checked";
            } else {
              $checked = "";
            }
?>
        <label><input type="checkbox" id="sr_answer_<?=$i?>_<?=($j+1)?>" name="sr_answer_<?=$i?>[]" value="<?=($j+1)?>"<?=$checked?>><?=$rows_a["sa_text"]?></label><br>
<?          
          }
        }
        
        if ($sq_to != "") {
          if ($check_arr[$num_rows_a] == true) {
            $checked = " checked";
          } else {
            $checked = "";
          }       
?>
        <label><input type="checkbox" id="sr_answer_<?=$i?>_<?=($num_rows_a+1)?>" name="sr_answer_<?=$i?>[]" value="<?=($j+1)?>"<?=$checked?>>기타: </label><input type="text" name="sr_answer_others_<?=$i?>" value="<?=$check_answer?>">
<?
        }
?>
        </p>
<?
        break;
      case 1: // 점수형
        echo($sq_text."<p>");
        
        for ($k = 0; $k < 11; $k++)
        {
          if ($sr_answer != "" && $sr_answer== $k + 1) {
            $checked = " checked";
          } else {
            $checked = "";
          }
?>
<input type="radio" name="sr_answer_<?=$i?>" value="<?=($k+1)?>"<?=$checked?>><?=($k*10)?>점 
<?
          if (($k+1) % 3 == 0) {
?>        
      <br>
<?
          }
        }
        echo("</p>");
        break;

      case 2: // 선택형
        echo($sq_text."<p>");
        
        for ($k = 0; $k < 3; $k++)
        {
          if ($sr_answer != "" && $sr_answer== $k + 1) {
            $checked[$k] = " checked";
          } else {
            $checked[$k] = "";
          }
        }
?>

<input type="radio" name="sr_answer_<?=$i?>" value="1"<?=$checked[0]?>>항상 그렇다<br>
<input type="radio" name="sr_answer_<?=$i?>" value="2"<?=$checked[1]?>>보통 그렇다<br>
<input type="radio" name="sr_answer_<?=$i?>" value="3"<?=$checked[2]?>>그렇지 않다<br>        
<?      
        echo("</p>");
        break;
      case 3: // 주관식 숫자
        $sq_text = str_replace("\${number}", "<input type=\"number\" name=\"sr_answer_$i\" min=\"0\" max=\"999\" size=\"2\" value=\"$sr_answer\" maxlength=\"3\">", $sq_text);
?>
    <?=$sq_text?>
<?        
        break;
      case 4: // 년월형
        $sq_text = str_replace("\${year}", "<input type=\"number\" name=\"year_$i\" size=\"2\" maxlength=\"2\" value=\"$year\" min=\"0\" max=\"99\">", $sq_text);
        $sq_text = str_replace("\${month}", "<input type=\"number\" name=\"month_$i\" size=\"2\" maxlength=\"2\" value=\"$month\" min=\"0\" max=\"11\">", $sq_text);
?>
    <?=$sq_text?>
<?        
        break;
    }
?>
</p>
<? 
  }
?>
<input type="hidden" name="sq_idx" value="<?=$sq_idx?>">
<input type="hidden" name="sd_idx" value="<?=$sd_idx?>">

<input type="submit" id="save" value="저장하기" disabled>
<?
  if ($page > 1) {
    // prev page
?>
<input type="button" id="prev" onClick="location.href='survey.html?sd_idx=<?=$sd_idx?>&page=<?=$page-1?>'" value="이전">
<?
  } else if ($page == 1 && $sd_idx > 1) {
    // prev division의 last page를 알아야 함
    
    $query_q1 = "select  count(*) cnt from sv_qlist where sd_idx = $sd_idx-1";
    $result_q1 = mysql_query($query_q1);
    $rows_q1 = mysql_fetch_array($result_q1);
    $prev_count = $rows_q1["cnt"];
    if ($prev_count == 0)
      $prev_page = 1;
    else
      $prev_page = floor(($prev_count - 1) / $perpage) + 1;
?>
  <input type="button" id="prev" onClick="location.href='survey.html?sd_idx=<?=$sd_idx-1?>&page=<?=$prev_page?>&curpage=<?=$curpage-1?>'" value="이전">
<?
  } 
  
  if ($count > $page_start + $num_rows_q) 
  { // next page 존재
?>
  <input type="button" id="next" style="display:none"   onClick="location.href='survey.html?sd_idx=<?=$sd_idx?>&page=<?=$page+1?>&curpage=<?=$curpage+1?>'" value="다음">
<?
  } else if ($sd_idx < 2) {
    // next division 존재
?>
<input type="button"  id="next" style="display:none" onClick="location.href='survey.html?sd_idx=<?=$sd_idx+1?>&curpage=<?=$curpage+1?>'" value="다음">
<?
  } 
?>
<input type="button" id="confirm" style="display:none" onClick="goConfirm();" value="설문 완료">
<?
  //echo("page_start[$page_start] num_rows_q[$num_rows_q]<br>");
?>


</form>
<p>총 <?=$page_total?>쪽 중 <?=$curpage?>쪽</p>
<iframe id="ifr" src="about:blank" name="ifr" width="300" height="300" style="display:none"></iframe>

<script>
  var prev = document.getElementById("prev");
  var next = document.getElementById("next");
  var timer;
  
<?
    if ($sd_idx == 1) {
      $total = $num_rows_q * 2;
    } else if ($sd_idx == 2) {
      $total = $num_rows_q * 3;
    }

?>
  var total = <?=$total?>;
  
  function showTimer()
  {
    var save = document.getElementById("save");
    
    if (total > 0) {
      total = total - 1;
      save.value = total + "초 후 저장 가능";
    } else {
      save.value = "저장하기";
      save.disabled = false;
      clearInterval(timer);
    }
  }
  
  function load() 
  {
    var save = document.getElementById("save");
    if (validation(1) == true) {
      first = false;  
      
      console.log("prev: " + prev + " next: " + next);
      if (prev)
        prev.style.display = "inline-block";
      if (next)
        next.style.display = "inline-block";
        
      save.disabled = false;
    } else {  // timer 
      save.value = total + "초 후 저장 가능";
      timer = setInterval("showTimer();", 1000);
    }
    
<?
  if ($quest_cnt == $solved_cnt) { 
?>
    document.getElementById("confirm").style.display = "inline-block";
<?
  }
?>
  }
</script>
</body>
</html>
<?
  include "common/db_close.php";
?>
